package com.fengye.common.interceptor;

import com.fengye.common.constants.AppHttpCodeEnum;
import com.fengye.common.exception.BusinessException;
import com.fengye.common.utils.JwtUtil;
import com.fengye.common.constants.CommonConstant;
import com.fengye.common.utils.StringUtils;
import com.fengye.common.utils.TokenExtractorUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author fengye
 * @description 登录拦截器，目前用security验证登录状态，这个拦截器废弃
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = TokenExtractorUtils.getHeaderBearerToken(request);
        //判断token是否为空，如果为空也代表未登录 提醒重新登录（401）
        if(StringUtils.isBlank(token)) {
            //response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            //return false;
            throw new BusinessException(AppHttpCodeEnum.UNAUTHORIZED);
        }
        //解析token看看是否成功
        try {
            String username = JwtUtil.parseUserId(token);
            System.out.println(username);
        } catch (Exception e) {
            e.printStackTrace();
            //如果解析过程中没有出现异常说明是登录状态
            //如果出现了异常，说明未登录，提醒重新登录（401）
            //response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            //return false;
            throw new BusinessException(AppHttpCodeEnum.TOKEN_INVALID);
        }
        return true;
    }
}
